package com.morgan.basemodule.viewmodel

import android.view.View
import androidx.lifecycle.*
import com.morgan.basemodule.view.IBaseView
import com.morgan.basemodule.view.ILifecycleCallback
import com.morgan.basemodule.view.LifecycleObserverImpl
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch

/**
 *description：
 *<br>author：caowugao
 *<br>time：2021/1/27 0027 17:29
 */
open class BaseVM : ViewModel(), ILifecycleCallback {

    val commonError : MutableLiveData<Throwable> by lazy { MutableLiveData<Throwable>() }

    val clickEvent : MutableLiveData<View> by lazy { MutableLiveData() }

    fun attachUI(owner: LifecycleOwner) {
        LifecycleObserverImpl(owner, true).addCallback(this)
    }

    fun onClick(v : View) {
        clickEvent.value = v
    }

    fun launch(block : suspend () -> Unit, error : (() -> Unit)? = null, cancel : (() -> Unit)? = null ) {
        viewModelScope.launch(CoroutineExceptionHandler{ _, e ->
            when (e) {
                is CancellationException -> {
                    cancel?.invoke()
                }
                else -> {
                    error?.invoke()
                }
            }
        }) {
            block.invoke()
        }
    }


    override fun onCreate() {
    }

    override fun onResume() {
    }

    override fun onPause() {
    }

    override fun onStop() {
    }

    override fun onDestroy() {
    }


}